<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"
      xmlns:shiro="http://www.pollix.at/thymeleaf/shiro">
<head>
    <meta charset="UTF-8">
    <title>广告成效数据</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <meta name="apple-mobile-web-app-status-bar-style" content="black">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="format-detection" content="telephone=no">
    <link rel="stylesheet" href="/layui/css/layui.css" media="all" />
    <link rel="stylesheet" href="/css/public.css" media="all" />

</head>
<body class="childrenBody">
<!-- 数据表格开始-->
<style>
    /* 统一按钮样式 */
    #trainPlanToolBar button,
    #trainPlanRowBar button {
        min-width: 100px;
        margin-right: 8px;
    }
</style>

<div>
    <table class="layui-hide" id="trainPlanTable" lay-filter="trainPlanTable"></table>
    <button lay-options="{accept: 'file'}" id="importExcel" style="display: none;"></button>

    <div id="trainPlanToolBar" style="display: none;">
        <button type="button" lay-event="add" shiro:hasPermission="trainPlan:create" class="layui-btn layui-btn-sm">
            <span class="layui-icon layui-icon-add-1"></span> 添加
        </button>
        <button type="button" lay-event="batchDelete" shiro:hasPermission="trainPlan:delete" class="layui-btn layui-btn-sm layui-btn-danger">
            <span class="layui-icon layui-icon-delete"></span> 批量删除
        </button>
        <button type="button" lay-event="toggleSortByPCount" class="layui-btn layui-btn-sm layui-btn-warm">
            <span class="layui-icon layui-icon-sort"></span> 曝光量排序
        </button>
        <button type="button" lay-event="exportExcel" class="layui-btn layui-btn-sm layui-bg-orange">
            <span class="layui-icon layui-icon-export"></span> 导出Excel
        </button>
        <button type="button" lay-event="importExcel" class="layui-btn layui-btn-sm">
            <span class="layui-icon layui-icon-upload-circle"></span> 导入Excel
        </button>
    </div>

    <div id="trainPlanRowBar" style="display: none;">
        <button type="button" lay-event="update" shiro:hasPermission="trainPlan:update" class="layui-btn layui-btn-sm">
            <span class="layui-icon layui-icon-edit"></span> 编辑
        </button>
        <button type="button" lay-event="delete" shiro:hasPermission="trainPlan:delete" class="layui-btn layui-btn-sm layui-btn-danger">
            <span class="layui-icon layui-icon-delete"></span> 删除
        </button>
    </div>
</div>

<!-- 添加和修改的弹出层开始 -->
<div style="display: none;padding: 5px" id="addOrUpdateDiv">
    <form action="" method="post" class="layui-form layui-form-pane" id="dataFrm" lay-filter="dataFrm">
        <div class="layui-form-item">
            <label class="layui-form-label">广告标题</label>
            <div class="layui-input-block">
                <input type="hidden" name="id" id="id">
                <input type="text" name="title"  lay-verify="required" autocomplete="off"  placeholder="广告标题" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
    <label class="layui-form-label">广告名称</label>
    <div class="layui-input-block">
        <select name="adName" id="adNameSelect" lay-verify="required" lay-filter="adNameSelect">
            <option value="">--请选择广告名称--</option>
        </select>
    </div>
</div>
        <div class="layui-form-item">
    <label class="layui-form-label">广告平台</label>
    <div class="layui-input-block">
        <select name="adPlatform" id="adPlatformSelect" lay-verify="required" lay-filter="adPlatformSelect">
            <option value="">--请选择广告平台--</option>
        </select>
    </div>
</div>






        <div class="layui-form-item">
            <label class="layui-form-label">曝光量</label>
            <div class="layui-input-block">
                <input type="text" name="pcount"  lay-verify="required" autocomplete="off" placeholder="曝光量" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">点击量</label>
            <div class="layui-input-block">
                <input type="text" name="dcount" lay-verify="required" autocomplete="off" placeholder="点击率" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">转化次数</label>
            <div class="layui-input-block">
                <input type="text" name="zcount"  lay-verify="required" autocomplete="off" placeholder="转化次数" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">点击率</label>
            <div class="layui-input-block">
                <input type="text" name="ctr" id="ctr" readonly placeholder="自动计算" class="layui-input layui-disabled">
            </div>
        </div>

        <div class="layui-form-item">
            <label class="layui-form-label">花费</label>
            <div class="layui-input-block">
                <input type="text" name="price"  lay-verify="required" autocomplete="off" placeholder="花费" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <div class="layui-input-block" style="text-align: center;">
                <button type="button" class="layui-btn" lay-submit="" lay-filter="doSubmit" id="doSubmit" ><span class="layui-icon layui-icon-add-1"></span>提交</button>
                <button type="reset" class="layui-btn layui-btn-warm" id="dataFrmResetBtn"><span class="layui-icon layui-icon-refresh-1"></span>重置</button>
            </div>
        </div>
    </form>
</div>
<!-- 添加和修改的弹出层结束 -->


<script type="text/javascript" src="/layui/layui.js"></script>

<script type="text/javascript">
    layui.use(['jquery','form','table','layer','laydate','upload'],function(){

        var $=layui.jquery;
        var form=layui.form;
        var table=layui.table;
        var layer=layui.layer;
        var laydate=layui.laydate;
        var upload = layui.upload;

        // 自动计算点击率（CTR）
        function updateCTR() {
            let pcount = parseFloat($("input[name='pcount']").val());
            let dcount = parseFloat($("input[name='dcount']").val());

            if (!isNaN(pcount) && !isNaN(dcount) && pcount !== 0) {
                let ctr = (dcount / pcount * 100).toFixed(2) + "%";
                $("#ctr").val(ctr);
            } else {
                $("#ctr").val("");
            }
        }
        // 渲染
        upload.render({
            elem: '#importExcel', // 绑定多个元素
            url: '/trainPlan/importExcel', // 此处配置你自己的上传接口即可
            accept: 'file', // 普通文件
            done: function(res){
                layer.msg('上传成功');
                console.log(res);
            }
        });


        // 曝光量/点击量/转化次数字段合法性限制
        $("input[name='pcount'], input[name='dcount'], input[name='zcount']").on("input", function () {
            let p = parseInt($("input[name='pcount']").val());
            let d = parseInt($("input[name='dcount']").val());
            let z = parseInt($("input[name='zcount']").val());

            if ($(this).attr("name") === "pcount") {
                if (isNaN(p) || p < 0) {
                    layer.msg("曝光量必须是非负整数");
                    $(this).val("");
                }
            }

            if ($(this).attr("name") === "dcount") {
                if (isNaN(d) || d < 0) {
                    layer.msg("点击量必须是非负整数");
                    $(this).val("");
                } else if (!isNaN(p) && d > p) {
                    layer.msg("点击量不能大于曝光量");
                    $(this).val(p);
                }
            }

            if ($(this).attr("name") === "zcount") {
                if (isNaN(z) || z < 0) {
                    layer.msg("转化次数必须是非负整数");
                    $(this).val("");
                } else if (!isNaN(d) && z > d) {
                    layer.msg("转化次数不能大于点击量");
                    $(this).val(d);
                }
            }

            updateCTR();  // 每次更新完都重新计算CTR
        });

// 监听曝光量和点击量输入事件
        $("input[name='pcount'], input[name='dcount']").on("input", function () {
            updateCTR();
        });


          //   初始化时间选择器
        laydate.render({
            elem:'#trainDate',
            type:'datetime'
        });

        //加载 数据
        var tableIns=table.render({
            elem: '#trainPlanTable'
            ,url:'/trainPlan/loadAlltrainPlan'
            ,toolbar: '#trainPlanToolBar' //开启头部工具栏，并为其绑定左侧模板
            ,title: '广告成效数据表'
            ,height:'full-77'
            ,page: true
            ,cols: [ [
                {type: 'checkbox', fixed: 'left'}
                ,{field:'id', title:'ID',align:'center'}
                ,{field:'adName', title:'广告名称',align:'center'}
                ,{field:'title', title:'广告标题',align:'center'}
                ,{field:'adPlatform', title:'投放平台',align:'center'}
                ,{field:'pcount', title:'曝光量',align:'center'}
                ,{field:'dcount', title:'点击量',align:'center'}
                ,{field:'ctr', title:'点击率',align:'center'}
                ,{field:'zcount', title:'转化次数',align:'center'}
                ,{field:'price', title:'花费',align:'center'},
               // 修改操作列的配置，增加宽度
{
  fixed: 'right',
  title:'操作',
  toolbar: '#trainPlanRowBar',
  align:'center',
  width: 200 // 设置合适的宽度
}

            ] ]
        });
        //监控模糊查询按钮事件
        form.on("submit(doSearch)", function (data) {
            tableIns.reload({
                where: data.field,
                page: {
                    curr: 1
                }
            });
            return false;
        });

        //监听工具条的事件
table.on("toolbar(trainPlanTable)", function (obj) {
    switch (obj.event) {
        case 'exportExcel':
            location.href = '/trainPlan/exportExcel';
            break;
        case 'toggleSortByPCount':
            toggleSortByPCount();
            break;
        case 'batchDelete':
            batchDelete();
            break;
        case "importExcel":
            $('#importExcel').click();
            break
        case 'add':
            openAddLayer();
            break;
    }
});



        //监听行工具条的事件
        table.on("tool(trainPlanTable)",function(obj){
            var data = obj.data; //获得当前行数据
            switch(obj.event){
                case 'update':
                    openUpdatetrainPlanLayer(data);
                    break;
                case 'delete':
                    deletetrainPlan(data);
                    break;

            };
        });
        var mainIndex;
        var url;
        //打开添加的弹出层
        function openAddLayer(){
            mainIndex=layer.open({
                type:1,
                content:$("#addOrUpdateDiv"),
                area:['800px','600px'],
                title:'发布考核',
                maxmin: true,
                success:function(){
                    $("#dataFrm")[0].reset();
                    url="/trainPlan/addtrainPlan";
                }
            });
        };
var sortState = 'desc'; // 默认排序方式

function toggleSortByPCount() {
    var sortField = "pcount";
    var sortOrder = sortState === 'desc' ? "desc" : "asc";

    // 切换排序状态
    sortState = sortState === 'desc' ? 'asc' : 'desc';
    layer.msg(sortState === 'desc' ? '降序排列中...' : '升序排列中...');

    // 重新加载数据并带上排序参数
    table.reload("trainPlanTable", {
        url: "/trainPlan/loadAlltrainPlan",
        where: {
            sortField: sortField,
            sortOrder: sortOrder
        },
        page: {
            curr: 1 // 回到第一页
        }
    });
}



        // 加载广告平台下拉框
function loadAdPlatforms() {
    $.get('/trainPlan/loadAdPlatforms', function(res) {
        if (res.code === 200 && res.data) {
            var select = $('#adPlatformSelect');
            select.empty().append('<option value="">--请选择广告平台--</option>');
            $.each(res.data, function(index, platformTitle) {
                select.append('<option value="' + platformTitle + '">' + platformTitle + '</option>');
            });
            layui.form.render('select'); // 渲染下拉框
        }
    });
}

// 初始化加载广告平台
loadAdPlatforms();

        // 加载广告名称下拉框
function loadAdNames() {
    $.get('/trainPlan/loadAdNames', function(res) {
        if (res.code === 200 && res.data) {
            var select = $('#adNameSelect');
            select.empty().append('<option value="">--请选择广告名称--</option>');
            $.each(res.data, function(index, adName) {
                select.append('<option value="' + adName + '">' + adName + '</option>');
            });
            layui.form.render('select'); // 渲染下拉框
        }
    });
}

// 初始化加载广告名称
loadAdNames();


        //打开修改的弹出层
     function openUpdatetrainPlanLayer(data){
    mainIndex=layer.open({
        type:1,
        content:$("#addOrUpdateDiv"),
        area:['800px','600px'],
        title:'修改广告计划',
        maxmin: true,
        success:function(){
            form.val("dataFrm", data); // 回填数据，包括 adPlatform
            url="/trainPlan/updateTrainPlan";
            form.render('select'); // 重新渲染下拉框
        }
    });
}



        //保存
        form.on("submit(doSubmit)",function(data){
            console.log(JSON.stringify(data.field));
            $.post(url,data.field,function(res){
                if(res.code==200){
                    tableIns.reload();
                }
                layer.msg(res.msg);
                layer.close(mainIndex);
            })
            return false;
        });

        //删除
        function deletetrainPlan(data){
            layer.confirm('你确定要删除这条数据吗?', {icon: 3, title:'提示'}, function(index){
                $.post("/trainPlan/deleteTrainPlan",{id:data.id},function(res){
                    if(res.code==200){
                        tableIns.reload();
                    }
                    layer.msg(res.msg);
                });
                layer.close(index);
            });
        };

        //批量删除
        function  batchDelete(){
            //得到选中行
            var checkStatus = table.checkStatus('trainPlanTable');
            var dataLength=checkStatus.data.length;
            if(dataLength>0){
                layer.confirm('你确定要删除这些数据吗?', {icon: 3, title:'提示'}, function(index){
                    var data=checkStatus.data; //获取选中行的数据
                    var ids="";
                    $.each(data,function(index,item){
                        if(index==0){
                            ids+="ids="+item.id;
                        }else{
                            ids+="&ids="+item.id;
                        }
                    })
                    $.post("/trainPlan/batchDeleteTrainPlan",ids,function(res){
                        if(res.code==200){
                            tableIns.reload();
                        }
                        layer.msg(res.msg);
                    })
                    layer.close(index);
                });

            }else{
                layer.msg("请选中操作行");
            }
        };

    });


</script>
</body>
</html>
